//
//  WLLComposePictureView.swift
//  WLLWeibo
//
//  Created by 王乐乐 on 16/8/17.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
//cell 重用标识
private let WLLComposePictureViewCellId = "WLLComposePictureViewCellId"

class WLLComposePictureView: UICollectionView {
    
    //保存 image 的数组
    var  imageList : [UIImage] = [UIImage]()
    //声明闭包
    var closure :(()->())?
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 供外界调用的方法
    func addImages(image:UIImage) {
        //添加到数组中
        imageList.append(image)
        //刷新UI
        reloadData()
        
    }
    
    //MARK: - 设置视图
    private func setupUI() {
        
        backgroundColor = UIColor.whiteColor()
        // 注册
        registerClass(WLLComposePictureViewCell.self , forCellWithReuseIdentifier: WLLComposePictureViewCellId)
        
        //MARK: -  //设置代理
        dataSource = self
        delegate = self
        //设置 layout
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        //cell 间距
        let cMargin:CGFloat = 5
        //cell 宽高
        let cellWH :CGFloat = (KSCREENW - 20 - 2*cMargin)/3
        //设置 itemsize
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        //设置垂直和水平间距
        layout.minimumLineSpacing = cMargin
        layout.minimumInteritemSpacing = cMargin
        
    }
    
    
    
    
    
    
    
}


extension WLLComposePictureView:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        /*
         - 如果 显示为 0 或者为 9 没有加号图片
         - 反之 其他 后面 显示加号图片
         */
        let count = imageList.count
        
        return  (count == 0 || count == 9) ? count : count+1
        //        if count == 0 || count == 9 {
        //            return count
        //
        //
        //        return imageList.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WLLComposePictureViewCellId, forIndexPath: indexPath) as! WLLComposePictureViewCell
        /*
         [1,2,3]  数组.count  3
         item =  0 , 1 ,2
         
         */
        
        if imageList.count == indexPath.item{
            cell.image = nil
        }else{
            
            //赋值
            cell.image = imageList[indexPath.item]
            //实例化 cell 的闭包/每个 cell 都对应一个闭包?!
            cell.cell_closure = {[weak self] in
                self?.imageList.removeAtIndex(indexPath.row)
                
                if self?.imageList.count == 0 {
                    //如果没图片了,隐藏 pictureView
                    self?.hidden = true
                }
                //刷新数据
                self?.reloadData()
            }
            
            
            
        }
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        
        if imageList.count == indexPath.item {
            closure?()
        }
    }
    
    
}





//MARK: - 自定义 cell
class WLLComposePictureViewCell : UICollectionViewCell{
    
    //声明一个闭包
    var cell_closure :(()->())?
    
    
    //供外界调用
    var image : UIImage?{
        didSet{//
            if image == nil {//加号图片
                bgImageView.image = UIImage(named:"compose_pic_add")
                bgImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                //隐藏删除按钮
                deleteButton.hidden = true
            }else{
                bgImageView.image = image
                //解决 cell 复用的问题
                bgImageView.highlightedImage = nil
                //显示删除按钮
                deleteButton.hidden = false
                
                
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        backgroundColor = RandomColor()
        
        //添加控件
        contentView.addSubview(bgImageView)
        contentView.addSubview(deleteButton)
        //添加约束
        bgImageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        deleteButton.snp_makeConstraints { (make) in
            make.top.trailing.equalTo(contentView)
        }
        
        
        
    }
    /**
     删除按钮的点击事件
     */
    func deleteAction() {
        printLog("删除按钮点击")
        cell_closure?()
        
        
    }
    
    //MARK: - 懒加载控件
    ///配图
    private lazy var bgImageView : UIImageView = UIImageView()
    /// 删除按钮
    private lazy var deleteButton: UIButton = {
        let btn = UIButton()
        btn.addTarget(self, action: "deleteAction", forControlEvents: UIControlEvents.TouchUpInside)
        btn.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        return btn
    }()
}










